import {getParamsFromCommand,validProdVersion} from './utils.js'
import fs from 'node:fs'
import path from 'node:path'
import axios from 'axios'
import dayjs from 'dayjs'
import archiver from 'archiver'
//显示声明导入的是json文件
import pkg from '../package.json' assert { type: 'json' }
const { withDist = false, prod = 0 } = getParamsFromCommand(process.argv)
const name = pkg.name
const zipDist = (name,format) =>{
    const ext = format === 'zip' ? '.zip' : '.tar.gz'
    const archive = archiver(format, { zlib: 9, gzip: true, gzipOptions: { level: 8 } })
    const output = fs.createWriteStream(`${name}${ext}`)
    const folderPath = `dist`
    archive.on('error', err => {
        console.error(err)
        throw err
    })
    archive.on('end', () => {
        console.log(`生成             ${name}${ext} 成功`)
    })
    archive.pipe(output)
    archive.directory(folderPath, '', { name: '', date: dayjs().add(8, 'hour').format('YYYY-MM-DD HH:mm:ss') })
    archive.finalize()
}

const genPubVersion = (pkgVersion) =>{
    const [major, minor, patch] = pkgVersion.split('.')
    const patchArr = patch.split('-')
    patchArr[0] = patchArr[0].padStart(2, '0')
    return minor + '.' + patchArr.join('-')
}


const writeFiles = version => {
    const defConfigPath = path.resolve(process.cwd(), 'dist/pub/defConfig.json')
    const isProdVersion = validProdVersion(version) ///\d{6}[59].\d{2}$/.test(version)
    const newDefConfigStr =
        JSON.stringify(
            {
                VERSION: version,
                env: isProdVersion ? 'prod' : 'test'
            },
            null,
            4
        ) + '\n'
    fs.writeFileSync(defConfigPath, newDefConfigStr)
}

console.log('package.json    ',pkg.version)
const pubVersion =  genPubVersion(pkg.version)
console.log('pubVersion      ', pubVersion)
writeFiles(pubVersion)
if (withDist) {
    zipDist('dist', 'zip')
}
console.log('压缩            ', `${name}.${pubVersion}`)
zipDist(`${name}.${pubVersion}`,'tar')